<template>
  <div class="uploadCard-warpper">
    <div class="topBox">
      <span>上传身份证</span>
    </div>
    <div class="photoBox">
      <div class="fontBox">
        <div class="text">身份证正面</div>
        <div class="bgBox">
          <div :class="[fontImg?'hide':'','camera']">
            <input type="file" name="font" accept="image/*" @change='addFontImg($event,"fontImg","fontImg2")'>
          </div>
          <img v-if="fontImg&&showFont" :src="fontImg">
        </div>
      </div>
      <div class="fengeBar"></div>
      <div class="backBox">
        <div class="text">身份证背面</div>
        <div class="bgBox">
          <!-- <div class="inputMask"> -->
            <div :class="[backImg?'hide':'','camera']">
              <input type="file" name="back" accept="image/*" @change='addBackImg($event,"backImg","backImg2")'>
            </div>
          <!-- </div> -->
          <img v-if="backImg&&showBack" :src="backImg">
        </div>
      </div>
    </div>
    <div class="next-box flex">
      <!-- <div class="picture" :style="'backgroundImage:url('+headerImage+')'"></div> -->
      <div @click="handleSubmit">提交审核</div>
    </div>
  
    <!-- 测试 -->
    <!-- <div class="album-img-list">
      <ul>
        <li v-for="img in imgList"><div class="album-bg-img"><img  :src='img.src'> </div></li>
      </ul>
    </div>
    <div class="album">
      <label for="img-upload">上传照片</label>
      <image-upload :img-arr.sync="imgList"></image-upload>
    </div> -->
  </div>
</template>

<script>
  import axios from '@/api/request'
  import fetch from '@/utils/fetch'
  import Vue from 'vue';
  // import imageUpload from '../components/imgUpload.vue'
  import { Group,XInput } from "vux";
  import Exif from 'exif-js'
  import { mapState } from "vuex";

  export default {
    name: '',
    components: {
      Group,
      XInput,
      // imageUpload
    },
    data () {
      return {
        showFont: false,
        showBack: false,
        fontImg: '',
        fontImg2: '',
        font: {
          fontImg: '',
          fontImg2: '',
        },
        back: {
          fontImg: '',
          fontImg2: '',
        },
        backImg: '',
        backImg2: '',
        fontReady: false,
        backReady: false,
        imgList: [],
        imgData: {  
            accept: 'image/gif, image/jpeg, image/png, image/jpg',  
        },
        headerImage:'',picValue:'',
        cardId: '',
        realname: '',
        shopName: '',
      }
    },
    computed:{
        ...mapState({
          openId:state=>state.openId,
          userId:state=>state.userId,
          schoolId:state=>state.schoolId,
          phone:state=>state.phone,  //手机号
        }),
    },
    created(){
      this.cardId = this.$route.query.card;
      this.realname = this.$route.query.realname;
      this.shopName = this.$route.query.shopName;
    },
    mounted(){
      // console.log(fetch.defaults.baseURL)
    },
    methods:{
      handleSubmit(){
        if(this.showFont&&this.showBack){
          let data = {
                shopName: this.shopName,
                shopType: '735279aea3ef4c7fb780b120f9b160a1',
                phone: this.phone,
                cardId: this.cardId,
                userId: this.userId,
                username: this.realname,
                schoolId: this.schoolId,
                cardFrontImg: this.fontImg2,
                cardBackImg: this.backImg2,
          }
          // alert(data.cardFrontImg+':'+data.cardBackImg)
          axios('/device/shopApplySecond/saveShopApplySecond','post',data).then(res=>{
              if(res.data.code==1000){
                  console.log(res)
                  this.$vux.toast.text('提交成功,请等待审核', 'middle')
                  this.$router.go(-2)   //返回个人中心页
              }
          })
        }else{
          this.$vux.toast.text('请先上传图片再提交', 'middle')
        }
      },
      addFontImg(e,img,img2){ 
        let files = e.target.files || e.dataTransfer.files;  
        if (!files.length) return; 
        this.uploadImg(files,img2).then(res=>{
          console.log(res)
          // img2 = res.data
          // this[img2] = res.data
          this.fontImg2 = fetch.defaults.baseURL+res.data
          this.showFont = true
          // alert(this.fontImg2)
          // this.fontImg2 = res.data
        }) 

        this.picValue = files[0];  
        this.imgPreview(this.picValue,img);
      },
      imgPreview (file,imgsrc) {  
        let self = this;
        let Orientation;  
        //去获取拍照时的信息，解决拍出来的照片旋转问题  
        Exif.getData(file, function(){  
            Orientation = Exif.getTag(this, 'Orientation');  
        });  
        // 看支持不支持FileReader  
        if (!file || !window.FileReader) return;  
  
        if (/^image/.test(file.type)) {  
          // 创建一个reader  
          let reader = new FileReader(); 

          // 将图片2将转成 base64 格式  
          reader.readAsDataURL(file);  
          // 读取成功后的回调  
          reader.onloadend = function () {  
            let result = this.result;  
            let img = new Image();  
            img.src = result;  
            //判断图片是否大于100K,是就直接上传，反之压缩图片  
            if (this.result.length <= (100 * 1024)) {  
              // self.fontImg = this.result; 
              self[imgsrc] = this.result; 
              // self.postImg(self,this.result);  
            }else {  
              img.onload = function () {  
                let src = self.compress(img,Orientation);  
                self[imgsrc] = self.compress(img,Orientation); 
                // self.fontImg = src;  
                // self.postImg(self,src);  
              }  
            }  
          }   
        }  
      },
      compress(img,Orientation) {  
        let self = this
        let canvas = document.createElement("canvas");  
        let ctx = canvas.getContext('2d');  
        //瓦片canvas  
        let tCanvas = document.createElement("canvas");  
        let tctx = tCanvas.getContext("2d");  
        let initSize = img.src.length;  
        let width = img.width;  
        let height = img.height;  
        //如果图片大于四百万像素，计算压缩比并将大小压至400万以下  
        let ratio;  
        if ((ratio = width * height / 4000000) > 1) {  
          console.log("大于400万像素")  
          ratio = Math.sqrt(ratio);  
          width /= ratio;  
          height /= ratio;  
        } else {  
          ratio = 1;  
        }  
        canvas.width = width;  
        canvas.height = height;  
        //   铺底色  
        ctx.fillStyle = "#fff";  
        ctx.fillRect(0, 0, canvas.width, canvas.height);  
          //如果图片像素大于100万则使用瓦片绘制  
        let count;  
        if ((count = width * height / 1000000) > 1) {  
          console.log("超过100W像素");  
          count = ~~(Math.sqrt(count) + 1); //计算要分成多少块瓦片  
          //       计算每块瓦片的宽和高  
          let nw = ~~(width / count);  
          let nh = ~~(height / count);  
          tCanvas.width = nw;  
          tCanvas.height = nh;  
          for (let i = 0; i < count; i++) {  
            for (let j = 0; j < count; j++) {  
              tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh);  
              ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);  
            }  
          }  
        } else {  
          ctx.drawImage(img, 0, 0, width, height);  
        }  
        //修复ios上传图片的时候 被旋转的问题  
        if(Orientation != "" && Orientation != 1){  
          switch(Orientation){  
            case 6://需要顺时针（向左）90度旋转  
                this.rotateImg(img,'left',canvas);  
                break;  
            case 8://需要逆时针（向右）90度旋转  
                this.rotateImg(img,'right',canvas);  
                break;  
            case 3://需要180度旋转  
                this.rotateImg(img,'right',canvas);//转两次  
                this.rotateImg(img,'right',canvas);  
                break;  
          }  
        }  
        //进行最小压缩  
        let ndata = canvas.toDataURL('image/jpeg', 0.1);  
        console.log('压缩前：' + initSize);  
        console.log('压缩后：' + ndata.length);  
        console.log('压缩率：' + ~~(100 * (initSize - ndata.length) / initSize) + "%");  
        tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;  
        self.fontReady = true
        return ndata;  
      },
      rotateImg (img, direction,canvas) {  
        //最小与最大旋转方向，图片旋转4次后回到原方向      
        const min_step = 0;      
        const max_step = 3;        
        if (img == null)return;      
        //img的高度和宽度不能在img元素隐藏后获取，否则会出错      
        let height = img.height;      
        let width = img.width;        
        let step = 2;      
        if (step == null) {      
            step = min_step;      
        }      
        if (direction == 'right') {      
            step++;      
            //旋转到原位置，即超过最大值      
            step > max_step && (step = min_step);      
        } else {      
            step--;      
            step < min_step && (step = max_step);      
        }       
        //旋转角度以弧度值为参数      
        let degree = step * 90 * Math.PI / 180;      
        let ctx = canvas.getContext('2d');      
        switch (step) {      
          case 0:      
              canvas.width = width;      
              canvas.height = height;      
              ctx.drawImage(img, 0, 0);      
              break;      
          case 1:      
              canvas.width = height;      
              canvas.height = width;      
              ctx.rotate(degree);      
              ctx.drawImage(img, 0, -height);      
              break;      
          case 2:      
              canvas.width = width;      
              canvas.height = height;      
              ctx.rotate(degree);      
              ctx.drawImage(img, -width, -height);      
              break;      
          case 3:      
              canvas.width = height;      
              canvas.height = width;      
              ctx.rotate(degree);      
              ctx.drawImage(img, -width, 0);      
              break;  
        }      
      },
      postImg(that,src){
        // this.$axios1({
        //   method: 'post',
        //   url: "http://172.17.1.157:8080/image/upload",
        //   data: {
        //       fileBase64: src,
        //       authType: '1'
        //   },  
        //   transformRequest: [function (data,headers) {
        //       let ret = ''
        //       for (let it in data) {
        //       ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
        //       }
        //       return ret
        //   }],
        //   headers: {
        //      'Content-Type': 'application/x-www-form-urlencoded'
        //   },
        //   headers: {'X-Requested-With': 'XMLHttpRequest'},
        //   responseType: 'json', // default
        // })
        let a = src.split('base64,')[1]
        this.$axios1.post('http://172.17.1.157:8080/image/upload3', {
          base64: a,
        })
        .then((res) => {
          console.log(res)
          // if(res.data.code == 0){
          //    that.imageFrontPath = res.data.data.path;
          //    if(res.data.data.info){
          //        if(res.data.data.info.address){
          //            that.idCardFrontDialogAddress = res.data.data.info.address;
          //        }
          //        if(res.data.data.info.name){
          //            that.idCardFrontDialogName = res.data.data.info.name;
          //        }
          //        if(res.data.data.info.number){
          //            that.idCardFrontDialogId = res.data.data.info.number;
          //        }
          //    }
          //    that.idCardFrontDialog = true;
          //    that.isFrontSuccess = true;
          //    that.imageFront = src;
          // }else{
          //    // setTimeout(() => {
          //    //     that.isDialogShow = true;
          //    // },100);
          //    // that.dialogTit = '图片上传失败';
          //    console.log('图片上传失败')
          // }
        })
        .catch((error) => {
           // that.isLoadingShow = false;
           // setTimeout(() => {
           //     that.isDialogShow = true;
           // },100);
           // that.dialogTit = '服务器错误';
           // console.log('错误了'+ error);
        });
      },
      addBackImg(e,img,img2){
        let files = e.target.files || e.dataTransfer.files;  
        if (!files.length) return; 
        this.uploadImg(files,img2).then(res=>{
          // console.log(res)
          // img2 = res.data
          // this[img2] = res.data
          this.backImg2 = fetch.defaults.baseURL+res.data
          this.showBack = true
          // alert(this.backImg2)
          // this.backImg2 = res.data
        }) 

        this.picValue = files[0];  
        this.imgPreview(this.picValue,img);
      }
    }
  };
</script>

<style >
    body{
        position: absolute;
        left: 0;
        top: 0;
        /*background: rgb(244,244,244);*/
        width: 100%;
        height: 100%;
        overflow: hidden;
    }
</style>
<style lang="less" scoped>
  .uploadCard-warpper{
    height: 100%;
    box-sizing: border-box;
    background: #fff;
    .topBox{
      height: 96rem/75;
      line-height: 96rem/75;
      background: #f2f3f6;
      span{
        margin-left: 30rem/75;
        font-size: 26rem/75;
        color: #999;
      }
    }
    .photoBox{
      .fontBox{
        overflow: hidden;
        height: 460rem/75;
        .bgBox{
          background: url(../assets/images/fontbg.png) no-repeat;
          background-size: 100% 100%;
          img{
            width: 100%;
            height: 100%;
            // width: 492rem/75;
            // height: 282rem/75;
            position: absolute;
            left: 0;
            top: 0;
            z-index: 999;
          }
        }
        .text{
          margin-top: 47rem/75;
        }
      }
      .fengeBar{
        margin: 0 40rem/75;
        height: 1px;
        background: #ddd;
      }
      .backBox{
        overflow: hidden;
        height: 471rem/75;
        .bgBox{
          background: url(../assets/images/backbg.png) no-repeat;
          background-size: 100% 100%;
          img{
            width: 100%;
            height: 100%;
            // width: 492rem/75;
            // height: 282rem/75;
            position: absolute;
            left: 0;
            top: 0;
            z-index: 999;
          }
        }
        .text{
          margin-top: 58rem/75;
        }
      }
      .bgBox{
        overflow: hidden;
        width: 492rem/75;
        height: 282rem/75;
        margin-left: 128rem/75;
        text-align: center;
        position: relative;
        .inputMask{
          width: 100%;
          height: 100%;
          padding-top: 68rem/75; 
          padding-bottom: 68rem/75; 
          padding-left: 178rem/75;
        }
        .camera{
          height: 136rem/75;
          width: 136rem/75;
          margin-top: 68rem/75;
          margin-left: 178rem/75;
          background: url(../assets/images/cardcamera.png) no-repeat;
          background-size: 100% 100%;
          z-index: 1001;
          input{
            width: 100%;
            height: 100%;
            opacity: 0;
          }
        }
        .hide.camera{
          display: none;
          // opacity: 0;
        }
      }
      .text{
        text-align: center;
        height: 30rem/75;
        line-height: 30rem/75;
        font-size: 30rem/75;
        margin-top: 47rem/75;
        margin-bottom: 30rem/75;
        color: #000;
      }
    }
    .next-box{
      width: 100%;
      justify-content: center;
      margin-top: 8rem/75;
      div{
        width: 600rem/75;
        height: 104rem/75;
        line-height: 104rem/75;
        background: #ffda44;
        color: #333;
        text-align: center;
        font-size: 35rem/75;
        border-radius: 8rem/75;
      }
    }
  }

</style>

